//
//  GPSExerciseStepTableViewCell.swift
//  DaFit
//
//  Created by Paul on 2022/10/27.
//  Copyright © 2022 sylar. All rights reserved.
//

import UIKit
import MYModule

open class GPSTrainingStepTableViewCell: TableViewCell {
    
    public var type: TrainingType = .unknown

    public let rateVerticalStackView = TitleStackView()
    public let strideVerticalStackView = TitleStackView()
    public let timeHorizontalStackView = TitleStackView()
    public let rateLabel: Label = {
        let lab = Label()
        lab.textColor = UIColor.assist_222222
        lab.font = .systemFont(ofSize: 30, weight: .heavy)
        lab.text = "0"
        return lab
    }()
    
    public let rateSubLabel: Label = {
        let lab = Label()
        lab.textColor = UIColor.assist_222222
        lab.font = .systemFont(ofSize: 12)
        lab.text = "gps_training_finish_steps_stride_avg_rate_title".language
        return lab
    }()
    
    public let strideLabel: Label = {
        let lab = Label()
        lab.textColor = UIColor.assist_222222
        lab.font = .systemFont(ofSize: 30, weight: .heavy)
        lab.text = "0.00"
        return lab
    }()
    
    public let strideSubLabel: Label = {
        let lab = Label()
        lab.textColor = UIColor.assist_222222
        lab.font = .systemFont(ofSize: 12)
        lab.text = "gps_training_finish_steps_stride_avg_stride_title".language
        return lab
    }()
    
    open var rate: [Double] = []{
        didSet{
            if rate != oldValue{
                var avg = 0.0
                var total = 0.0
                var count = 0
                for i in rate{
                    if i != 0{
                        total += i
                        count += 1
                    }
                }
                if count > 0 {
                    avg = total/Double(count)
                }
                avgRate = avg
                drawChart(chart: rateChartView, data: rate, color: UIColor.GPSTraining.theme, MaxValue: 200)
                
            }
        }
    }
    open var stride: [Double] = []{
        didSet{
            if stride != oldValue{
                var avg = 0.0
                var total = 0.0
                var count = 0
                for i in stride{
                    if i != 0{
                        total += i
                        count += 1
                    }
                }
                if count > 0 {
                    avg = total/Double(count)
                }
                avgStride = avg
                drawChart(chart: strideChratView, data: stride, color: UIColor.theme, MaxValue: 2.0)
            }
        }
    }
    
    open var avgRate:Double = 0{
        didSet{
            rateLabel.text = avgRate.normalTitle//String(format: "%.0f",avgRate)
        }
    }
    
    open var avgStride:Double = 0{
        didSet{
            strideLabel.text = avgStride.normalTitle//String(format: "%.2f",avgStride)
        }
    }
    

    public let titleLabel = Label()
    public let chartLineView = ChartLineView(frame: CGRect(x: 0, y: 0, width: kScreenWidth - 75.0, height: 100))
    public let rateChartView = View(frame: CGRect(x: 0, y: 0, width: kScreenWidth - 90, height: 100))
    public let strideChratView = View(frame: CGRect(x: 0, y: 0, width: kScreenWidth - 90, height: 100))
    
    
    open override func makeUI() {
        
        self.selectionStyle = .none
        self.backgroundColor = UIColor.darkBackground
        
        let boxView = View()
        boxView.backgroundColor = .white
        boxView.layer.cornerRadius = 18.0
        
        contentView.addSubview(boxView)
        boxView.snp.makeConstraints { make in
            make.top.centerX.width.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
        
        titleLabel.text = "gps_training_finish_steps_stride_title".language
        titleLabel.font = Fonts.boldSystemFont(ofSize: 14)
        titleLabel.textColor = UIColor.assist_000000
        titleLabel.adaptive()
        
        boxView.addSubview(titleLabel)

        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(20)
            make.right.equalTo(-20)
        }
        

        let rateView = View(frame: CGRect(x: 0, y: 0, width: 6, height: 12))
        rateView.layer.cornerRadius = 3
        rateView.layer.masksToBounds = true
        rateView.backgroundColor = UIColor.GPSTraining.theme
        rateView.snp.makeConstraints { make in
            make.width.equalTo(6)
            make.height.equalTo(12)
        }
        
        let strideView = View(frame: CGRect(x: 0, y: 0, width: 6, height: 12))
        strideView.layer.cornerRadius = 3
        strideView.layer.masksToBounds = true
        strideView.backgroundColor = UIColor.theme
        strideView.snp.makeConstraints { make in
            make.width.equalTo(6)
            make.height.equalTo(12)
        }
        
        let rateSubstackView = UIStackView(arrangedSubviews: [rateView, rateSubLabel])
        rateSubstackView.alignment = .center
        rateSubstackView.axis = .horizontal
        rateSubstackView.distribution = .equalSpacing
        rateSubstackView.spacing = 4
        
        let strideSubstackView = UIStackView(arrangedSubviews: [strideView, strideSubLabel])
        strideSubstackView.alignment = .center
        strideSubstackView.axis = .horizontal
        strideSubstackView.distribution = .equalSpacing
        strideSubstackView.spacing = 4
        
        let rateStackView = UIStackView(arrangedSubviews:[rateLabel, rateSubstackView])
        rateStackView.alignment = .center
        rateStackView.axis = .vertical
        rateStackView.distribution = .fill
        
        let strideStackView = UIStackView(arrangedSubviews:[strideLabel, strideSubstackView])
        strideStackView.alignment = .center
        strideStackView.axis = .vertical
        strideStackView.distribution = .fill
        
        let infoStackView = UIStackView(arrangedSubviews: [rateStackView, strideStackView])
        infoStackView.alignment = .center
        infoStackView.axis = .horizontal
        infoStackView.distribution = .equalCentering
        infoStackView.spacing = 50
        
        boxView.addSubview(infoStackView)
        infoStackView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(24)
            make.centerX.equalToSuperview()
            make.height.equalTo(90)
        }
        
        rateVerticalStackView.axis = .vertical
        rateVerticalStackView.alignment = .trailing
        rateVerticalStackView.textColor = UIColor.assist_222222
        rateVerticalStackView.titles = ["200","150","100","50"," "]
        
        strideVerticalStackView.axis = .vertical
        strideVerticalStackView.alignment = .leading
        strideVerticalStackView.textColor = UIColor.assist_222222
        strideVerticalStackView.titles = ["2.0","1.5","1.0","0.5"," "]

        timeHorizontalStackView.axis = .horizontal
        timeHorizontalStackView.alignment = .top
        timeHorizontalStackView.font = Fonts.systemFont(ofSize: 11)
        timeHorizontalStackView.titles = ["0", "", "", "", "0"]

        boxView.addSubview(rateVerticalStackView)
        boxView.addSubview(strideVerticalStackView)
        boxView.addSubview(timeHorizontalStackView)
        boxView.addSubview(chartLineView)
        
        let rateUnitLab = Label()
        rateUnitLab.textColor = UIColor.GPSTraining.theme
        rateUnitLab.font = .systemFont(ofSize: 10)
        rateUnitLab.text = "gps_training_finish_steps_stride_avg_rate_unit".language
        rateUnitLab.textAlignment = .left
        
        let strideUnitLab = Label()
        strideUnitLab.textColor = UIColor.theme
        strideUnitLab.font = .systemFont(ofSize: 10)
        strideUnitLab.text = "gps_training_finish_steps_stride_avg_stride_unit".language
        strideUnitLab.textAlignment = .right
        
        let lineTitleStackView = UIStackView(arrangedSubviews: [rateUnitLab, strideUnitLab])
        lineTitleStackView.distribution = .fillEqually
        lineTitleStackView.axis = .horizontal
        lineTitleStackView.alignment = .fill
        
        boxView.addSubview(lineTitleStackView)
        lineTitleStackView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.left.equalTo(rateVerticalStackView.snp.left)
            make.right.equalTo(strideVerticalStackView.snp.right)
            make.bottom.equalTo(chartLineView.snp.top).offset(-15)
        }
        
        chartLineView.bottomLineColor = UIColor.assist_EEEEEE
        chartLineView.lineColor = UIColor.assist_EEEEEE

        chartLineView.snp.makeConstraints { make in
            make.left.equalTo(45)
            make.right.equalTo(-45)
            make.top.equalTo(infoStackView.snp.bottom).offset(30)
            make.height.equalTo(100)
            
            
        }

        rateVerticalStackView.snp.makeConstraints { make in
            make.right.equalTo(chartLineView.snp.left).offset(-5)
            make.top.equalTo(chartLineView.snp.top).offset(-8)
            make.bottom.equalTo(chartLineView.snp.bottom).offset(8)
        }
        
        strideVerticalStackView.snp.makeConstraints { make in
            make.left.equalTo(chartLineView.snp.right).offset(5)
            make.top.equalTo(chartLineView.snp.top).offset(-8)
            make.bottom.equalTo(chartLineView.snp.bottom).offset(8)
        }

        timeHorizontalStackView.snp.makeConstraints { make in
            make.left.equalTo(chartLineView.snp.left)
            make.right.equalTo(chartLineView.snp.right)
            make.top.equalTo(chartLineView.snp.bottom).offset(1)
            make.bottom.equalToSuperview().offset(-20)
        }

        boxView.addSubview(rateChartView)
        boxView.addSubview(strideChratView)
        rateChartView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(chartLineView)
        }
        strideChratView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(chartLineView)
        }
    }
    
    open func setHorizontalStackView(start: Date?, end: Date?) {
       
        var endDateStr = end?.toString(.custom("MM/dd HH:mm")) ?? "--"
        var startDateStr = start?.toString(.custom("MM/dd HH:mm")) ?? "--"
        
        startDateStr = "\(startDateStr)\("gps_training_start".language)"
        endDateStr = "\(endDateStr)\("gps_training_end".language)"
        
        timeHorizontalStackView.titles = [startDateStr, endDateStr]
    }
    
    
    open func drawChart(chart: View, data: [Double],color: UIColor, MaxValue: Double){
        let countHearts = data.count
        if countHearts < 1{
            return
        }
        chart.subviews.forEach { (subview) in
            subview.removeFromSuperview()
        }
        let chartHeight = chart.height
        let chartWidth = chart.width
        let rate = 1
        
        //数据个数
        var counts = 1
        if rate != 0 {
            counts = countHearts / rate
        }
        let barWidth = chartWidth / Double(counts - 1)
        var chartPoint: [CGPoint] = []
        for i in 0..<counts{
            let id  = i * rate
            let value = data[id]
            
            let heightRate = chartHeight / MaxValue
            var height = Double(value) * heightRate
            if height > chartHeight {
                height = chartHeight
            }
            var x = 0.0
            if i > 0{
                x = Double(i) * barWidth
            }
            chartPoint.append(CGPoint(x: x, y: Double(chartHeight) - height))
            
        }
        let linePath = UIBezierPath()
        linePath.lineWidth = 1
        linePath.move(to: chartPoint[0])
        if chartPoint.count < 2{
            let cp1 = CGPoint(x: (CGFloat(chartWidth) - chartPoint[0].x) / 2 + chartPoint[0].x, y: chartPoint[0].y )
            let cp2 = CGPoint(x: (CGFloat(chartWidth) - chartPoint[0].x) / 2 + chartPoint[0].x, y: chartHeight)
            linePath.addCurve(to: CGPoint(x: CGFloat(chartWidth), y: chartHeight), controlPoint1: cp1, controlPoint2: cp2)
        }else {
            for i in 1..<chartPoint.count{
                let cp1 = CGPoint(x: (chartPoint[i].x + chartPoint[i - 1].x) / 2 , y: chartPoint[i - 1].y)
                let cp2 = CGPoint(x: (chartPoint[i].x + chartPoint[i - 1].x) / 2 , y: chartPoint[i].y)
                linePath.addCurve(to: chartPoint[i], controlPoint1: cp1, controlPoint2: cp2)
            }
        }
        let lineLayer = CAShapeLayer()
        lineLayer.lineWidth = 2
        lineLayer.path = linePath.cgPath
        lineLayer.strokeColor = color.cgColor
        lineLayer.fillColor = UIColor.clear.cgColor
        
        let lineView = View()
        lineView.layer.addSublayer(lineLayer)
        chart.addSubview(lineView)
    }

}
